package com.example.train.controller;

import cn.hutool.core.collection.CollUtil;
import com.example.train.common.base.model.ResponseBase;
import com.example.train.model.SysPermission;
import com.example.train.service.SysPermissionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Collections;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/permission")
public class SysPermissionController {

    @Autowired
    private SysPermissionService sysPermissionService;

    @PostMapping
    public ResponseBase<Integer> add(@RequestBody @Valid SysPermission sysPermission){
        Integer insert = sysPermissionService.insert(sysPermission);
        if (insert == null) {
            return ResponseBase.failed("资源已存在");
        }
        return ResponseBase.success(insert);
    }

    @PutMapping
    public ResponseBase<Integer> update(@RequestBody SysPermission sysPermission){
        int i = sysPermissionService.updateByPrimaryKeySelective(sysPermission);
        if (i == 0) {
            return ResponseBase.failed("不存在该数据");
        }else{
            return ResponseBase.success(i);
        }
    }

    @DeleteMapping("/{id}")
    public ResponseBase<Integer> delete(@PathVariable Long id){
        int i = sysPermissionService.deleteByPrimaryKey(id);
        if (i == 0) {
            return ResponseBase.failed("不存在该数据");
        }else{
            return ResponseBase.success(i);
        }
    }

    @GetMapping("/{id}")
    public ResponseBase<SysPermission> get(@PathVariable Long id){
        List<SysPermission> sysPermissions = sysPermissionService.selectByPrimaryKeys(Collections.singletonList(id));
        if (CollUtil.isEmpty(sysPermissions)) {
            return ResponseBase.failed("不存在该数据");
        }
        return ResponseBase.success(sysPermissions.get(0));
    }

//    @GetMapping("/list")
//    public ResponseBase<List<Tree<Long>>> list(){
//        List<Tree<Long>> list = sysPermissionService.getPermissionList();
//        return ResponseBase.success(list);
//    }

    @PostMapping("/menuList")
    public ResponseBase<List<SysPermission>> list(@RequestBody(required = false) List<Long> ids) {
        if (ids != null && ids.contains(1L)) {
            ids = null;
        }
        List<SysPermission> list = sysPermissionService.selectAll(ids);
        return ResponseBase.success(list);
    }

}
